package vip.xiaonuo.dev.modular.wechat.controller;

import cn.hutool.core.bean.BeanUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import vip.xiaonuo.common.annotation.CommonLog;
import vip.xiaonuo.common.pojo.CommonResult;
import vip.xiaonuo.dev.modular.calender.entity.BizCalender;
import vip.xiaonuo.dev.modular.calender.param.BizCalenderAddParam;
import vip.xiaonuo.dev.modular.calender.param.BizCalenderEditParam;
import vip.xiaonuo.dev.modular.calender.service.BizCalenderService;
import vip.xiaonuo.dev.modular.wechat.param.WechatCalendarParam;
import vip.xiaonuo.dev.modular.wechat.param.wechatReq.*;
import vip.xiaonuo.dev.modular.wechat.param.WechatConfigParam;
import vip.xiaonuo.dev.modular.wechat.param.wechatReq.Calendar;
import vip.xiaonuo.dev.modular.wechat.service.DevWechatService;
import vip.xiaonuo.dev.modular.wechat.util.ase.WXBizMsgCrypt;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 企业微信控制器
 *
 * @author xsl
 * @date 2024-06-18 11:58
 **/
@Tag(name = "企业微信控制器")
@RestController
public class DevWechatController {

    private static Logger logger = LoggerFactory.getLogger(DevWechatController.class);

    @Resource
    private DevWechatService devWechatService;

    @Resource
    private BizCalenderService bizCalenderService;

    /**
     * 企业微信-发送消息推送
     */
    @Operation(summary = "发送企业微信消息推送")
    @CommonLog("推送企业微信消息")
    @PostMapping("/dev/wechat/sendMsg")
    public CommonResult<String> sendMsg(@RequestBody @Valid WechatMessageParam devWechatParam) {
        devWechatService.sendMsg(devWechatParam);
        return CommonResult.ok();
    }

    @Operation(summary = "获取网页页面的js设置")
    @CommonLog("获取网页页面的js设置")
    @GetMapping("/dev/wechat/getJsConfig")
    public CommonResult<WechatConfigParam> getJsConfig(@RequestParam(name = "url", required = false) String url) {
        logger.info("<---------------------------------------------------获取网页页面的js设置：{}--------------------------------------------------->", url);
        WechatConfigParam wechatConfigParam = devWechatService.getWechatJSConfig(url);
        return CommonResult.data(wechatConfigParam);
    }


    @Operation(summary = "同步企业微信部门信息")
    @CommonLog("同步企业微信部门信息")
    @GetMapping("/dev/wechat/asyncDepartment")
    public CommonResult<String> asyncDepartment() {
        logger.info("<---------------------------------------------------同步企业微信部门信息--------------------------------------------------->");
        WXBizMsgCrypt client = devWechatService.getCodeClient();
        try {
            devWechatService.syncWechatMember();
            return CommonResult.ok("部门信息同步成功");
        } catch (Exception e) {
            //验证URL失败，错误原因请查看异常
            return CommonResult.data("error");
        }
    }


    @Operation(summary = "通讯录的回调接口")
    @CommonLog("通讯录的回调接口")
    @PostMapping(path = "/dev/wechat/memberCallback",  produces = {MediaType.APPLICATION_XML_VALUE},  consumes = {MediaType.APPLICATION_XML_VALUE})
    public String memberCallback(@RequestBody @Valid WechatMemberCallbackParam wechatMemberCallbackParam) throws IOException {
        logger.info("<---------------------------------------------------企业微信通信录回调接口--------------------------------------------------->");
        logger.info("\n接收到来自微信服务器的企业微信通信录回调消息：signature = [{}], timestamp = [{}], nonce = [{}], echostr = [{}]",
                wechatMemberCallbackParam.getMsgSignature(), wechatMemberCallbackParam.getTimeStamp(), wechatMemberCallbackParam.getNonce(), wechatMemberCallbackParam.getEchoStr());
        String resStr = devWechatService.verifySign(wechatMemberCallbackParam.getMsgSignature(),wechatMemberCallbackParam.getTimeStamp(),  wechatMemberCallbackParam.getNonce(), wechatMemberCallbackParam.getEchoStr());
        devWechatService.callBackWechatMemberOrDepartment(wechatMemberCallbackParam);
        return resStr;
    }

    /**
     * 企业微信回调地址，用以接受参数(post请求)
     * @return
     */
    @Operation(summary = "企业微信回调地址")
    @CommonLog("企业微信回调地址")
    @PostMapping(value = "/dev/wechat/callback", produces = MediaType.APPLICATION_XML_VALUE,  consumes = MediaType.APPLICATION_XML_VALUE )
    public String authPost(@RequestBody @Valid WechatCallbackParam wechatCallbackParam) {
        logger.info("\n接收到来自微信服务器的用户回复消息：signature = [{}], timestamp = [{}], nonce = [{}], echostr = [{}]",
                wechatCallbackParam.getMsgSignature(), wechatCallbackParam.getTimestamp(), wechatCallbackParam.getNonce(), wechatCallbackParam.getEchostr());
        String resStr = devWechatService.verifySign(wechatCallbackParam.getMsgSignature(),wechatCallbackParam.getTimestamp(),  wechatCallbackParam.getNonce(), wechatCallbackParam.getEchostr());
        return resStr;
    }

    /**
     * 企业微信回调地址，用以接受参数(get请求)
     * @return
     */
    @CommonLog("验证回调URL有效性")
    @GetMapping("/dev/wechat/callback")
    public String callback(@RequestParam(name = "msg_signature") String msg_signature,
                                         @RequestParam(name = "timestamp") String timestamp,
                                         @RequestParam(name = "nonce") String nonce,
                                         @RequestParam(name = "echostr") String echostr	) {
        logger.info("\n验证回调URL有效性：signature = [{}], timestamp = [{}], nonce = [{}], echostr = [{}]", msg_signature, timestamp, nonce ,echostr);
        try {
            String res = devWechatService.verifySign(msg_signature,timestamp, nonce,echostr);
            logger.info("\n验证结果：{}", res);
            return res;
        } catch (Exception e) {
            //验证URL失败，错误原因请查看异常
            logger.error(e.getMessage());
            return "error";
        }
    }


    /**
     * 当父节点为集团时，同步集团各个子公司基本信息(get请求)
     * @return
     */
    @CommonLog("查询部门信息")
    @GetMapping("/dev/wechat/getOrgInfo")
    public CommonResult<String> getOrgInfo(@RequestParam(name = "orgId") String orgId,
                            @RequestParam(name = "departmentId") String departmentId) {
        logger.info("\n查询部门信息：orgName = [{}], departmentId = [{}]", orgId, departmentId);
        try {
            devWechatService.getDepartmentIdList(orgId, departmentId);
            return CommonResult.ok();
        } catch (Exception e) {
            logger.info(e.getMessage());
            //验证URL失败，错误原因请查看异常
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 当父节点为集团时，同步集团各个子公司基本信息(get请求)
     * @return
     */
    @CommonLog("查询部门员工信息")
    @GetMapping("/dev/wechat/getMemberInfo")
    public CommonResult<String> getMemberInfo(@RequestParam(name = "orgId") String orgId) {
        logger.info("\n查询部门员工信息：orgId = [{}]", orgId);
        try {
            devWechatService.getMemberInfo(orgId);
            return CommonResult.ok();
        } catch (Exception e) {
            logger.info(e.getMessage());
            //验证URL失败，错误原因请查看异常
            throw new RuntimeException("部门员工信息获取异常，请检查接口信息");
        }
    }

    /**
     * 基于党建重点任务，创建相关提醒日程（测试）
     * @return
     */
    @CommonLog("基于党建重点任务，创建相关提醒日程")
    @PostMapping("/dev/wechat/createCalendar")
    public CommonResult<String> createCalendar(@RequestBody @Valid List<WechatCalendarParam> reqList) {
        logger.info("\n创建任务提醒：任务类型 = [{}]",reqList.toString());
        try {
            // devWechatService.getMemberInfo(orgId);
            BizCalender bizCalender = bizCalenderService.updateByCropName("甘肃公航旅运输服务公司");
            String calId;
            String userIdOne = devWechatService.getUserIdByPhone("13993128506");
            String userIdTwo = devWechatService.getUserIdByPhone("18323891531");
            String userIdThird = devWechatService.getUserIdByPhone("17793195517");

            if(bizCalender==null){
                Calendar calendarParam = new Calendar();
                BizCalenderAddParam bizCalenderAddParam = new BizCalenderAddParam();
                bizCalenderAddParam.setCorpName("甘肃公航旅运输服务公司");
                bizCalenderAddParam.setColor(calendarParam.getColor());
                bizCalenderAddParam.setSummary("重要事项日历");
                calendarParam.setSummary("重要事项日历");
                bizCalenderService.add(bizCalenderAddParam);
                // 创建日历
                WechatCalendarParam wechatCalendarParam = new WechatCalendarParam();
                wechatCalendarParam.setCalendarParam(calendarParam);
                wechatCalendarParam.setSummary("重要事项日历");
                // 手机号获取用户userId
                Map<String ,String> shareOne = new HashMap<>();
                Map<String ,String> shareTwo = new HashMap<>();
                Map<String ,String> shareThird = new HashMap<>();
                shareOne.put("userid", userIdOne);
                shareOne.put("permission", "1");
                shareTwo.put("userid", userIdTwo);
                shareTwo.put("permission", "1");
                shareThird.put("userid", userIdThird);
                shareThird.put("permission", "1");

                List< Map<String ,String>> shares = new ArrayList<>();
                shares.add(shareOne);
                shares.add(shareTwo);
                shares.add(shareThird);


                calendarParam.setShares(shares);
                wechatCalendarParam.setCalendarParam(calendarParam);
                calId = devWechatService.createCalender(wechatCalendarParam);
                BizCalenderEditParam bizCalenderEditParam = new BizCalenderEditParam();
                BizCalender bizCalender1 = bizCalenderService.updateByCropName("甘肃公航旅运输服务公司");
                BeanUtil.copyProperties(bizCalenderEditParam, bizCalender1);
                bizCalender1.setCalId(calId);
                logger.info("创建的日历id:{}",calId);
                bizCalenderService.edit(bizCalenderEditParam);
            }else{
                calId = bizCalender.getCalId();
                reqList.forEach(item->{
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneOffset.UTC);
                    String startTime = item.getStartTime() + " 00:00:01";
                    LocalDateTime start = LocalDateTime.parse(startTime, formatter);
                    long startStamp = start.toEpochSecond(ZoneOffset.UTC);;
                    String endTime = item.getEndTime() + " 23:59:59";
                    LocalDateTime end = LocalDateTime.parse(endTime, formatter);
                    long endStamp = end.toEpochSecond(ZoneOffset.UTC);

                    Schedule scheduleParam = new Schedule();
                    scheduleParam.setSummary(item.getTitle());
                    scheduleParam.setDescription("重点工作内容："+item.getSummary()+"主要责任人员："+item.getMember());
                    scheduleParam.setEnd_time(endStamp);
                    scheduleParam.setStart_time(startStamp);

                    Map<String ,String> useOne = new HashMap<>();
                    Map<String ,String> useTwo = new HashMap<>();
                    Map<String ,String> useThird = new HashMap<>();

                    useOne.put("userid",userIdOne);
                    useTwo.put("userid",userIdTwo);
                    useThird.put("userid",userIdThird);

                    List<Map<String ,String>> attendees = new ArrayList<>();
                    attendees.add(useOne);
                    attendees.add(useTwo);
                    attendees.add(useThird);

                    scheduleParam.setAttendees(attendees);
                    Reminders remindersParam = new Reminders();
                    remindersParam.setRepeat_until(endStamp);
                    scheduleParam.setCal_id(calId);
                    WechatCalendarParam wechatCalendarParam = new WechatCalendarParam();
                    wechatCalendarParam.setScheduleParam(scheduleParam);
                    scheduleParam.setReminders(remindersParam);
                    String schId = devWechatService.createSchedule(wechatCalendarParam);
                    logger.info("创建的日程id:{}",schId);
                });
            }
            return CommonResult.ok();
        } catch (Exception e) {
            logger.info(e.getMessage());
            //验证URL失败，错误原因请查看异常
            throw new RuntimeException("任务创建失败");
        }
    }






}
